package daiwei.javaWeb.exam.controller;


import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import daiwei.javaWeb.exam.meta.Result;
import daiwei.javaWeb.exam.serviceImpl.DataBaseOPImpl;

@Controller
@RequestMapping("/api")
public class ApiController {

	@Autowired
	private DataBaseOPImpl dataBaseOp;
		
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(@RequestParam("userName") String username,@RequestParam("password") String password,
			HttpSession session, ModelMap map,Result result) throws Exception {
		if(dataBaseOp.getUser(username, password)!=null) {
			result.islogin(true);
			session.setAttribute("user", dataBaseOp.getUser(username, password));
		} else {
			result.islogin(false);
		}
		map.addAttribute("code", result.getCode());
		map.addAttribute("message", result.getMessage());
		map.addAttribute("result", result.getResult());
		return " ";
	}
	
	@RequestMapping(value="/buy",method=RequestMethod.POST)
	public String buy(Result result,@RequestParam int id,HttpSession session, ModelMap map) throws Exception {
		Result result1 =  dataBaseOp.buyProduct(session,id, result);
		map.addAttribute("code", result1.getCode());
		map.addAttribute("message", result1.getMessage());
		map.addAttribute("result", result1.getResult());
		return " ";
	}
	
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public String delete(Result result,@RequestParam int id,ModelMap map)  {
		try {
			dataBaseOp.deleteProduct(id);
			result.isdelete(true);
		} catch (Exception e) {
			result.isdelete(false);
			e.printStackTrace();
		}
		map.addAttribute("code", result.getCode());
		map.addAttribute("message", result.getMessage());
		map.addAttribute("result", result.getResult());
		return " ";
	}
}
